<template>
  <div class="shipping">
    <el-form :model="search" inline>
      <el-form-item>
        <el-input v-model="search.name" placeholder="模板名称" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-input v-model="search.mobile" placeholder="商家手机号码" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="searchHandle">搜索</el-button>
        <el-button type="primary" icon="el-icon-plus" @click="add">添加同城配送收费模板</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="tableData" style="width: 100%" border>
      <el-table-column label="商家名称" align="center" prop="sellerName" width="120" show-overflow-tooltip></el-table-column>
      <el-table-column label="商家手机号" align="center" prop="mobile" width="120"></el-table-column>
      <el-table-column label="模板名称" align="center" prop="name" width="120" show-overflow-tooltip></el-table-column>
      <el-table-column label="发货区域" align="center" width="120" prop='deliveryFromDistrict'></el-table-column>
      <el-table-column label="发货地址" align="center" width="160">
        <template slot-scope="scope">
          <span>{{scope.row.deliveryFromAddress}}</span>——
          <span>{{scope.row.deliveryFromDetail}}</span>
        </template>
      </el-table-column>
      <el-table-column label="配送范围" align="center" prop="deliveryConditionAmount" width="100">
      </el-table-column>
      <el-table-column label="起送金额" align="center" prop="deliveryConditionDistance" width="100"></el-table-column>
      <el-table-column label="计费方式" align="center">
          <template slot-scope="scope">
            <span style="color: red;font-weight: bold;">{{scope.row.firstDistance}}</span>
            公里内免费配送，超出后起步价
            <span style="color: red;font-weight: bold;">{{scope.row.firstPrice}}</span>
            元，每增加
            <span style="color: red;font-weight: bold;">{{scope.row.nextDistance}}</span>
            公里(不够1公里按1公里计算)，增加费用
            <span style="color: red;font-weight: bold;"> {{scope.row.nextPrice}}</span>
            元
          </template>
      </el-table-column>
      <el-table-column label="是否启用" align="center" width="100">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.isActive" @change="changeHandle(scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="160" fixed="right">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="update(scope.row)">编辑</el-button>
          <el-button type="danger" size="mini" @click="remove(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pages">
      <el-pagination :page-size="size" :current-page="page" layout="prev, pager, next,total,jumper" :total="total"
        background @current-change="handleCurrentChange">
      </el-pagination>
    </div>

    <el-dialog :title="title" :visible.sync="visible" width="70%">
      <el-form label-width="120px" :model="formData" :rules="rules" ref="ruleForm">
        <el-form-item label="商家名称">
          <span>{{merName}}</span>
        </el-form-item>
		<el-form-item label="商家手机号">
		  <el-input v-model="formData.mobile"></el-input>
		</el-form-item>
        <el-form-item label="模板名称">
          <el-input v-model="formData.name"></el-input>
        </el-form-item>
        <el-form-item label="配送说明">
          <el-input v-model="formData.description" type="textarea" :rows="2" placeholder="请输入内容"></el-input>
        </el-form-item>
        <el-form-item label="发货地址">
          <el-input v-model="formData.deliveryFromDetail" style="width: 260px;margin-right: 10px;" disabled="disabled"
            placeholder="发货地址"></el-input>
          <el-button icon="el-icon-location" @click="getMap()">地图</el-button>
        </el-form-item>
        <el-form-item label="配送范围">
          <span>发货地址</span>
          <el-input-number v-model="formData.deliveryConditionAmount" :min="0" controls-position="right" style="width: 120px;margin:0 10px;"></el-input-number>
          <span>公里范围内, 超过该范围不能配送</span>
        </el-form-item>
        <el-form-item label="起送金额">
          <el-input-number v-model="formData.deliveryConditionDistance" :min="0" controls-position="right" style="width: 120px;margin-right:10px;"></el-input-number>
          <span>元, 订单金额少于起送金额不能配送</span>
        </el-form-item>
        <el-form-item label="计费方式">
          <el-row>
            <el-col style="margin-bottom:15px;">
              <el-input-number v-model="formData.firstDistance" :min="0" controls-position="right" style="width: 120px;margin-right:10px;"></el-input-number>
              <span>公里内免费配送，超出后起步价</span>
              <el-input-number v-model="formData.firstPrice" :min="0" controls-position="right" style="width: 120px;margin:0 10px;"></el-input-number>
              <span>元，</span>
            </el-col>
            <el-col>
              <span>每增加</span>
              <el-input-number v-model="formData.nextDistance" :min="0" controls-position="right" style="width: 120px;margin:0 10px;"></el-input-number>
              <span>公里(不够1公里按1公里计算)，增加费用</span>
              <el-input-number v-model="formData.nextPrice" :min="0" controls-position="right" style="width: 120px;margin:0 10px;"></el-input-number>
              <span>元</span>
            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submit('ruleForm')" icon="el-icon-check">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog title="发货地址" :visible.sync="mapVisible" width="70%">
      <div class="map">
        <el-form ref="form">
          <el-form-item>
            <el-row :gutter="10">
              <el-col :span="21">
                <el-autocomplete v-model="formData.deliveryFromDetail" :fetch-suggestions="querySearchAsync2"
                  placeholder="输入关键字搜索" @select="handleSelect2" style="width: 100%;">
                  <template slot-scope="{ item }">
                    <div class="name">
                      <span>{{ item.name }}</span>
                      <span style="font-size: 12px;color: #ccc;padding-left: 5px;">{{ item.address.length?item.address:''}}</span>
                    </div>
                  </template>
                </el-autocomplete>
              </el-col>
              <el-col :span="3">
                <el-button type="primary" style="width: 100%;" @click="confirm">确定</el-button>
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>
        <div id="container"></div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        size: 10,
        page: 1,
        total: 0,
        search: {
          name: '',
          mobile: ""
        },
        tableData: [],
        title: '',
        visible: false,
		merName:localStorage.getItem('merName'),
        formData: {
          sellerName: '', //商家名称
          mobile: '', //商家手机号
          name: '', //模板名称
          description: '', //配送模板说明
          deliveryFromCode: '', //起送地址所在城市code
          deliveryFromAddress: '', //起送地址名称
          deliveryFromDistrict: '', //起送地址所在区
          deliveryFromDetail: '', //起送地址详细地址
          deliveryFromLongitude: '', //经度
          deliveryFromLatitude: '', //纬度
          deliveryConditionAmount: '', //最远配送距离(千米), 超过该距离不能配送
          deliveryConditionDistance: '', //起送金额(订单超过该金额才能配送)
          firstDistance: '', //配送起步距离(该距离内配送免费)
          firstPrice: '', //配送起步价
          nextDistance: '', //增加距离
          nextPrice: '', //增加价格
        },
        rules: {

        },
        restaurants: [],
        mapVisible: false,
        map: '',
        marker: '',
      }
    },
    mounted() {
      this.getData();
      this.getMerchantList();
    },
    methods: {
      getData() {
        this.$http.get(this.$api.deliverylist, {
          page: this.page,
          size: this.size,
          name: this.search.name,
          mobile: this.search.mobile,
		  merchantId:localStorage.getItem('merchantId')
        }).then(res => {
          this.tableData = res.data;
          this.total = res.extraInfo;
        })
      },
      confirm() {
        this.mapVisible = false;
      },
      searchHandle() {
        this.page = 1;
        this.getData();
      },
      handleCurrentChange(val) {
        this.page = val;
        this.getData();
      },
      getMerchantList() {
        this.$http.get(this.$api.merchantSimple, {
          query: ''
        }).then(res => {
          this.restaurants = res.data;
        })
      },
      querySearchAsync(queryString, cb) {
        var restaurants = this.restaurants;
        var merchantData = [];
        restaurants.forEach(item => {
          merchantData.push({
            mid: item.mid,
            mobile: item.usrPhone,
            value: item.namePhone
          });
        })
        var results = queryString ? merchantData.filter(this.createStateFilter(queryString)) : merchantData;
        cb(results);
      },
      createStateFilter(queryString) {
        return (state) => {
          return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
        };
      },
      changeHandle(row){
        this.$http.put(this.$api.deliveryIsActive, {
          isActive: row.isActive,
          transportId: row.id
        }).then(res => {
          if (res.code == 0) {
            this.$message({
              type: 'success',
              message: '修改成功!'
            });
          } else {
            this.$message({
              type: 'success',
              message: '修改失败!'
            });
          }
        })
      },
      handleSelect(val) {
        this.formData.sellerId = val.mid;
        this.formData.mobile = val.mobile;
      },
      add() {
        this.formData = {
          id:'',
		  sellerId:localStorage.getItem('merchantId'),
          sellerName: localStorage.getItem('merName'), //商家名称
          mobile: '', //商家手机号
          name: '', //模板名称
          description: '', //配送模板说明
          deliveryFromCode: '', //起送地址所在城市code
          deliveryFromAddress: '', //起送地址名称
          deliveryFromDistrict: '', //起送地址所在区
          deliveryFromDetail: '', //起送地址详细地址
          deliveryFromLongitude: '', //经度
          deliveryFromLatitude: '', //纬度
          deliveryConditionAmount: '', //最远配送距离(千米), 超过该距离不能配送
          deliveryConditionDistance: '', //起送金额(订单超过该金额才能配送)
          firstDistance: '', //配送起步距离(该距离内配送免费)
          firstPrice: '', //配送起步价
          nextDistance: '', //增加距离
          nextPrice: '', //增加价格
        },
        this.title = '添加同城配送收费模板';
        this.visible = true;
      },
      remove(row){
        this.$confirm('此操作将永久删除该运费模板, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http.delete(this.$api.deliveryDel + '/' + row.id).then(res => {
            if (res.code == 0) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
              this.getData();
            } else {
              this.$message.error('删除失败!');
            }
          })
        }).catch(() => {});
      },
      update(row){
        this.title = '修改同城配送收费模板';
        this.visible = true;
        this.formData = row;
		this.formData.sellerName = localStorage.getItem('merName');
      },
      getMap() {
        var self = this;
        this.mapVisible = true;
        setTimeout(function() {
          self.map = new AMap.Map('container', {
            resizeEnable: true
          });
        }, 0)
      },
      querySearchAsync2(queryString, cb) {
        AMap.plugin('AMap.PlaceSearch', function() {
          var placeSearch = new AMap.PlaceSearch({
            extensions: 'all'
          });
          placeSearch.search(queryString, function(status, result) {
            if (status === 'complete' && result.info === 'OK') {
              cb(result.poiList.pois);
            } else {
              cb([]);
            }
          });
        })
      },
      handleSelect2(item) {
        this.formData.deliveryFromDetail = item.name;
        this.formData.deliveryFromLongitude = item.location.lng;
        this.formData.deliveryFromLatitude = item.location.lat;
        this.formData.deliveryFromDistrict = item.pname + ' ' + item.cityname + ' '+item.adname; //起送地址所在区
        this.formData.deliveryFromAddress = item.address;
        this.formData.deliveryFromCode = item.adcode;
        this.setMarker();
      },
      setMarker() {
        var self = this;
        if (this.marker) {
          this.map.remove(this.marker);
        }
        this.marker = new AMap.Marker({
          position: new AMap.LngLat(self.formData.deliveryFromLongitude, self.formData.deliveryFromLatitude),
          title: self.value
        });
        this.map.add(this.marker);
        this.map.setZoomAndCenter(14, [self.formData.deliveryFromLongitude, self.formData.deliveryFromLatitude]);
      },
      submit(ruleForm) {
        this.$refs[ruleForm].validate((valid)=>{
            if(valid){
              if(this.formData.id){
                 this.$http.put(this.$api.deliveryUpdate,this.formData).then(res=>{
                   if (res.code == 0) {
                     this.$message({
                       type: 'success',
                       message: '修改成功'
                     });
                     this.visible = false;
                     this.getData();
                   } else {
                     this.$message.error('修改失败！');
                   }
                 })
              }else{
                this.$http.post(this.$api.deliveryAdd,this.formData).then(res=>{
                  if (res.code == 0) {
                    this.$message({
                      type: 'success',
                      message: '添加成功'
                    });
                    this.visible = false;
                    this.getData();
                  } else {
                    this.$message.error('添加失败！');
                  }
                })
              }

            }
        })
      }
    }
  }
</script>

<style scoped>
  .shipping {
    padding: 15px;
  }

  .pages {
    display: flex;
    justify-content: center;
    margin: 30px 0;
  }

  #container {
    width: 100%;
    height: 400px;
  }
</style>
